import datetime
from typing import Dict

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, text, ForeignKey, JSON
from sqlalchemy.orm import Session, relationship

from common.database import Base
from common.database import SessionMixin


class MonitorLogPolicy(Base, SessionMixin):
    __tablename__ = 'monitor_log_policy'
    policy_name = Column(String(128), nullable=False, comment="策略名称")  # 策略名称等于应用名称
    alarm_threshold = Column(Integer, nullable=False, comment="告警阈值")
    alarm_plan = Column(JSON, nullable=False, comment="告警计划-时间范围")
    is_maintain = Column(Boolean, default=text('true'), nullable=False, comment="维护模式")
    maintain_begin_time = Column(DateTime, nullable=True, comment="维护开始时间")
    maintain_end_time = Column(DateTime, nullable=True, comment="维护结束时间")
    notice_group = Column(JSON, default=list(), nullable=True, comment="通知群组")
    monitor_log_service_uuid = Column(Integer, ForeignKey('monitor_log_service.uuid'), nullable=False, comment="监控日志服务uuid")
    # policy2service = relationship('MonitorLogService', backref='service2policy')
    create_time = Column(DateTime, default=datetime.datetime.now, nullable=False, comment="创建时间")
    update_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, nullable=False,
                         comment="更新时间")
    __table_args__ = (
        Index('idx_monitor_log_policy_uuid', 'uuid', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return "<uuid='{}',policy_name='{}'>".format(self.uuid, self.policy_name)

    @classmethod
    def get_policy_by_service_name(cls, db: Session, service_name):
        return db.query(cls).filter(cls.policy_name == service_name).to_dict_first()
